package org.ssssssss.example.utils;


import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import java.io.*;



public class PdfUtils {

    private static final Logger log = LoggerFactory.getLogger(PdfUtils.class);

    public static boolean PDFRotate(String sourceFile, int rotate) throws IOException {

        File file = new File(sourceFile);
        PDDocument document = PDDocument.load(file);
        PDPageTree pages = document.getPages();
        for (PDPage page:pages){
            page.setRotation(rotate);
        }

        document.save(sourceFile);
        return true;

    }

    public static boolean PDFRotate(String sourceFile,String saveFile,int rotate) throws IOException {

        File file = new File(sourceFile);
        PDDocument document = PDDocument.load(file);
        PDPageTree pages = document.getPages();
        for (PDPage page:pages){
            page.setRotation(rotate);
            page.setArtBox(PDRectangle.A5);
        }

        document.save(saveFile);
        return true;

    }


    /**
     * pdf 转base64
     *
     * @param sourceFile
     * @return
     */
    public static String PDFToBase64(String sourceFile) {
        BASE64Encoder encoder = new BASE64Encoder();
        FileInputStream fin = null;
        BufferedInputStream bin = null;
        ByteArrayOutputStream baos = null;
        BufferedOutputStream bout = null;
        File file = new File(sourceFile);
        try {
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            baos = new ByteArrayOutputStream();
            bout = new BufferedOutputStream(baos);
            byte[] buffer = new byte[1024];
            int len = bin.read(buffer);
            while (len != -1) {
                bout.write(buffer, 0, len);
                len = bin.read(buffer);
            }
            //刷新此输出流并强制写出所有缓冲的输出字节
            bout.flush();
            byte[] bytes = baos.toByteArray();
            return encoder.encodeBuffer(bytes).trim();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            log.error("pdf转base64异常",e);

        } finally {
            try {
                fin.close();
                bin.close();
                bout.close();
            } catch (IOException e) {
                log.error("pdf转base64异常",e);
            }
        }
        return null;
    }

}
